package com.xindong.paking.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xindong.paking.entity.LoginResponseResult;
import com.xindong.paking.entity.TbUser;
import com.xindong.paking.mapper.TbUserMapper;
import com.xindong.paking.service.LoginService;
import com.xindong.paking.service.TbUserService;
import com.xindong.paking.utils.BCrypt;
import com.xindong.paking.utils.JwtUtil;
import com.xindong.paking.utils.Result;
import com.xindong.paking.utils.ResultStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public Result login(String username, String password) {

        // 查询账号
        QueryWrapper<TbUser> tbUserQueryWrapper = new QueryWrapper<>();
        tbUserQueryWrapper.eq("username", username);
        TbUser tbUser = tbUserMapper.selectOne(tbUserQueryWrapper);
        // 如果账号为空
        if (tbUser == null) {
            return new Result(ResultStatus.USER_PASSWORD_ERROR);
        }

        // 验证密码
        boolean check = BCrypt.checkpw(password, tbUser.getPassword());
        if (!check) {
            return new Result(ResultStatus.USER_PASSWORD_ERROR);
        }

        // 设置密码为空，返回前端用户信息
        tbUser.setPassword(null);

        // 将数据转入map当中
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap = JSON.parseObject(JSON.toJSONString(tbUser), new TypeReference<Map<String, Object>>() {});

        // 获取token
        String token = JwtUtil.sign(tbUser.getId().toString(), userMap);

        // 返回参数
        LoginResponseResult loginResponseResult = new LoginResponseResult(token, tbUser);

        //return new Result(200, "登陆成功", loginResponseResult);
        return Result.success("登陆成功", loginResponseResult);
    }

}
